package com.chenken;

import java.util.HashMap;
import java.util.Map;

/**
 * https://leetcode-cn.com/leetbook/read/tencent/xxqfy5/
 * @author ken.chen
 *	两数之和
 */
public class TwoSum {
	
	public static void main(String[] args) {
		int[] nums = {1,2,3,4,5,6,7,8,9};
		int[] twoSum = twoSum(nums,10);
		System.out.println("nums["+twoSum[0]+"],nums["+twoSum[1]+"]");
	}
	
	/**
	 * 依次扫描，扫描到6的时候，发现10-6=4存在于map中，所以返回
	 * @param nums
	 * @param target
	 * @return
	 */
    public static int[] twoSum(int[] nums, int target) {
    	if(nums.length == 0) return null;
    	Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    	for(int i = 0;i<nums.length;i++) {
    		int complement = target - nums[i];
    		if (map.containsKey(complement)) {
                return new int[] { map.get(complement), i };
            }
            map.put(nums[i], i);
    	}
		return nums;
    }
}
